package com.taobao.machinesystem.component;

import com.alibaba.fastjson.JSON;
import com.taobao.machinesystem.anno.MachineLog;
import com.taobao.machinesystem.entity.SysLog;
import com.taobao.machinesystem.entity.SysUser;
import com.taobao.machinesystem.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.apache.shiro.subject.Subject;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 切面 日志 主要写系统操作日志
 */
@Component
@Aspect
public class MachineLogAspect {

    @Autowired
    private SysLogService sysLogService;

    /**
     * 切点方法 所有controller的方法执行都插入日志
     */
    @Pointcut(value = "execution(public * com.taobao.machinesystem.controller.*.*(*) )")
    public void writeLog() {

    }

    /**
     * 前置通知
     */
//    @Before(value = "writeLog()")
    public void beforeWriteLog() {

    }
    @AfterReturning(value = "writeLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    /**
     * 后置通知·
     */
    @After(value = "writeLog()")
    public void afterWriteLog(JoinPoint joinPoint) {
        SysLog sysLog  = new SysLog();
        //开始时间
        long startTime = System.currentTimeMillis();
        //转换为实现类
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //获取方法对象
        Method method = methodSignature.getMethod();
        //获取方法名称
        String methodName = method.getName();
        //判断方法是否含有MachineLog
        if (method.isAnnotationPresent(MachineLog.class)) {
            MachineLog annotation = method.getAnnotation(MachineLog.class);
            //得到记录的log日志
            String value = annotation.value();

            sysLog.setValue(value);
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //操作人员shiro来
        Subject subject = SecurityUtils.getSubject();
        SysUser sysUser = (SysUser) subject.getPrincipal();
        sysLog.setName(sysUser.getUsername());
        //操作地址request来
        String ipAddress =request.getLocalAddr();
        //操作路劲request来
        String uri = request.getRequestURI();
        //操作完整路劲request来
        String url = request.getRequestURL().toString();
        //请求方式
        String requestMethod = request.getMethod();

        //请求参数获取
        Object parameter = getParameter(method, joinPoint.getArgs());
        //结束时间
        long endTime = System.currentTimeMillis();

        sysLog.setIp(ipAddress);
//        sysLog.setName();
        sysLog.setTime((int) (startTime - endTime));
        sysLog.setParameter(JSON.toJSONString(parameter));
        sysLog.setUri(uri);
        sysLog.setUrl(url);
        sysLog.setMethod(requestMethod);

        sysLogService.save(sysLog);
    }

//    @After("后置通知")


    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        List<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            //将RequestBody注解修饰的参数作为请求参数
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            if (requestBody != null) {
                argList.add(args[i]);
            }
            //将RequestParam注解修饰的参数作为请求参数
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestParam != null) {
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (!StringUtils.isEmpty(requestParam.value())) {
                    key = requestParam.value();
                }
                map.put(key, args[i]);
                argList.add(map);
            }
        }
        if (argList.size() == 0) {
            return null;
        } else if (argList.size() == 1) {
            return argList.get(0);
        } else {
            return argList;
        }
    }
}
